package cn.com.iresearch.android.componentizationsupporter

import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.winterbe.expekt.should
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*


/**
Created By: Seal.Wu
Date: 2018/4/3
Time: 11:02
 */
@RunWith(AndroidJUnit4::class)
class TestComponentCommunication {


    companion object {
        @BeforeClass
        @JvmStatic
        fun initEnvironment() {
            val context = InstrumentationRegistry.getContext()
            ComponentRouter.init(context)
        }
    }

    @Test
    fun invokeComponentOneFunction() {
        val context = InstrumentationRegistry.getTargetContext()
        val componentOne = ComponentRouter.getComponent("TestComponentOne")
        componentOne.execute("toast", context)
        /**
         * 为了让Toast显示时间长点
         */
        Thread.sleep(1 * 1000)
        componentOne.execute("log")
        componentOne.execute("getComponentKey").should.be.equal("TestComponentOne")
    }

    @Test
    fun invokeComponentOneAsyncFunction() {
        val componentOne = ComponentRouter.getComponent("TestComponentOne")
        var hasBackCall = false
        var tobeReturnDate:Date = Date()
        componentOne.executeAsync("getTime", callback = {
            if (it is Date) {
               tobeReturnDate = it
                hasBackCall = true
            }
        })

        /**
         * 一直等待直到回调方法被执行
         */
        while (hasBackCall.not()) {
            Thread.sleep(1 * 100)
        }
        tobeReturnDate.time.should.be.equal(1234567890)
    }

    @Test
    fun invokeComponentTwoFunction() {
        val context = InstrumentationRegistry.getTargetContext()
        val componentOne = ComponentRouter.getComponent("TestComponentTwo")
        componentOne.execute("toast", context)
        /**
         * 为了让Toast显示时间长点
         */
        Thread.sleep(1 * 1000)
        componentOne.execute("log")
        componentOne.execute("getComponentKey").should.be.equal("TestComponentTwo")
    }

    @Test
    fun invokeEmptyComponent() {
        val componentNone = ComponentRouter.getComponent("TestComponentNone")
        componentNone.should.be.equal(EmptyComponent)
        componentNone.execute("AnyCommand")
        var hasBackCall = false

        componentNone.executeAsync("AnyCommand",0,0,0,0,callback = {
            hasBackCall = true
        })
        hasBackCall.should.be.`true`
    }
}